package com.qk.web.interceptor;

import com.qk.utils.CurrentUserHoler;
import com.qk.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 28188
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor{


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String url = request.getRequestURI();

        if (url.contains("login")){
            log.info("用户登录: {}", request.getParameterMap());
            return true;
        }

        // 验证令牌
        String jwt = request.getHeader("token");
        if (jwt == null || jwt.isEmpty()){
            log.info("用户未登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // 解析令牌
        try{
            Claims claims = JwtUtils.parseToken(jwt);
            Integer userId = claims.get("id", Integer.class);
            CurrentUserHoler.setCurrentUser(userId);
        }catch (Exception e){
            log.info("解析令牌失败, 返回错误结果");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        // 放行
        log.info("用户已登录: {}", request.getParameterMap());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        CurrentUserHoler.removeCurrentUser();
    }

}
